<?php


namespace app\admin\controller;


use app\admin\common\library\FlowEngine;
use app\admin\common\WorkTime;
use app\admin\model\Approval;
use app\admin\model\AuthGroup;
use app\admin\model\Budget;
use app\admin\model\Caigou;
use app\admin\model\Che;
use app\admin\model\FlowInstance;
use app\admin\model\FlowNumber;
use app\admin\model\FlowScheme;
use app\admin\model\FlowTask;
use app\admin\model\Item;
use app\admin\model\JournaLevel;
use app\admin\model\JournalType;
use app\admin\model\JournWeek;
use app\admin\model\Money;
use app\admin\model\Overtime;
use app\admin\model\ProjectBudget;
use app\admin\model\ProjectBudgetPlanConfig;
use app\admin\model\ProjectBudgetTypeConfig;
use app\admin\model\ProjectPlan;
use app\admin\model\WorkJournal;
use app\admin\model\Zhang;
use app\BaseController;

use think\Config;
use think\facade\Db;
use think\facade\View;
use think\Request;

class Myworkitem extends BaseController
{
    protected $model = null;
    protected $task = null;
    protected $flow = null;
    protected $currentNode = null;
    protected $nextNode = null;
    protected $scheme = null;
    protected $instance = null;
    protected $prefix = "";
    protected $adminModel = null;
    protected $number = null;
    protected $sum_jbd = null;

    public function initialize()
    {
        parent::initialize();
        $this->task = new FlowTask();
        $this->instance = new FlowInstance();
        $this->scheme = new \app\admin\model\Scheme();
        $this->adminModel = new \app\admin\model\Admin();
        $this->number = new FlowNumber();
        $this->sum_jbd =
            \app\admin\model\Overtime::where(['user_id'  => $this->auth->id,
                                              'is_leave' => 0,
                                              'status'   => 2])
                ->sum('duration');

    }

    //显示
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');

            $where = array();
            if ($request->has('instancecode') && !empty($request->get('instancecode'))) {
                $where[] = array("instancecode", "like", "%" . $request->get('instancecode') . "%");
            }
            if ($request->has('flowname') && !empty($request->get('flowname'))) {
                $where[] = array("flowname", "like", "%" . $request->get('flowname') . "%");
            }
            if ($request->has('stepname') && !empty($request->get('stepname'))) {
                $where[] = array("stepname", "like", "%" . $request->get('stepname') . "%");
            }
            if ($request->has('nickname') && !empty($request->get('nickname'))) {
                $where[] = array("nickname", "like", "%" . $request->get('nickname') . "%");
            }
//            if ($request->has('createtime') && !empty($request->get('createtime'))) {
//                $where[] = array("createtime", "=", $request->get('createtime'));
//            }
//            if ($request->has('completedtime') && !empty($request->get('completedtime'))) {
//                $where[] = array("completedtime", "=", $request->get('completedtime'));
//            }
            $where[] = array("status", "=", 0);
            $where[] = array("receiveid", "=", $this->auth->id);
            $total = Db::name('view_workitem')
                ->where($where)
                ->order('createtime desc')
                ->count();
            $list = Db::name('view_workitem')
                ->where($where)
                ->order('createtime desc')
                ->page($page, $limit)
                ->select();

            return json(['code' => 200, 'msg' => '', 'total' => $total, 'data' => $list]);
        }
        return View::fetch();
    }

    //NEXT
    public function edit(Request $request)
    {
        $journal_level = JournaLevel::select();
        $table = $request->param('table');
        $ids = $request->param('ids');
        $row = Db::name($table)->find($ids);
        $cg = Db::name('cg_type')->field('id,name,price')->select();
        $plan = ProjectPlan::where('status', 1)->select(); //查询计划
        if (!$row)
            return json(['code' => 400, 'url' => '', 'msg' => 'No Results were found(未找到结果)']);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                return json(['code' => 400, 'url' => '', 'msg' => 'You have no permission(你没有权限)']);
            }
        }
        $taskid = $request->param('taskid');
        $task = null;
        $mode = $request->param('mode');
        if ($mode == 'view') {
            $task = $this->task->where(['id' => $taskid])->find();
        } else {
            $task = $this->task->where(['id' => $taskid])->where('status', 0)->find();
        }
        if (!$task)
            return json(['code' => 400, 'url' => '', 'msg' => '找不到当前任务']);
        $schme = $this->scheme->find($task['flowid']);
        if ($task['from_table'] == "vacations") { //请假
            $model = \app\admin\model\Vacation::find($task['from_id']);
            if (empty($model)) {
                return "找不到该资源";
            }
            $model = \app\admin\model\Vacation::checkDetail($model['id']);
            if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $model->corresponding, $match)) {
                //含有汉字
                $model['is_number'] = 1;
            } else {
                //不含有汉字
                $model['is_number'] = 2;
            }
            $model['sum_jbd'] =  $this->sum_jbd;
            $src = "detail/vacation_detail";
        } else if ($task['from_table'] == "applies") { //申请
            $model = \app\admin\model\Applies::with(['typeName'])->find($task['from_id']);
            if (empty($model)) {
                return "找不到该资源";
            }
            if ($model->typeName->name == "借款") {
                $money = Db::name('applies_money')->where('applies_id', $task['from_id'])->find();
                if (empty($model)) {
                    return "找不到该借款，请联系管理员";
                }
                $money['dx'] = get_amount($money['jk_money']);
                $model['money'] = $money;
            } else if ($model->typeName->name == "用章") {
                $zhang = Db::name('applies_zhang')->where('applies_id', $task['from_id'])->find();
                if (empty($model)) {
                    return "找不到该信息，请联系管理员";
                }
                $model['zhang'] = $zhang;
            } else if ($model->typeName->name == "用车") {
                $che = Db::name('applies_che')->where('applies_id', $task['from_id'])->select();
                if (empty($che)) {
                    return "找不到该信息，请联系管理员";
                }
                $model['che'] = $che;
            } else if ($model->typeName->name == "采购") {
                $caigou = Caigou::with('type')->where('applies_id', $task['from_id'])->select();
                if (empty($caigou)) {
                    return "找不到该信息，请联系管理员";
                }
                $model['caigou'] = $caigou;
            } else {
                $model = "";
            }
            $src = "detail/applies_detail";
        } else if ($task['from_table'] == "journals") { //日志
            $model = WorkJournal::with('week')->find($task['from_id']);
            if (empty($model)) {
                return "找不到该日志，请联系管理员";
            }
            $src = "detail/journals_detail";
        } else if ($task['from_table'] == "projects") { //项目
            $model = Item::with('dept')->find($task['from_id']);
            if (empty($model)) {
                return "找不到该项目，请联系管理员";
            }
            $src = "detail/projects_detail";
        } else if ($task['from_table'] == "budget") { //预算
            $model = Budget::with(['pb'=>['ProjectBudgetPlanConfig' => ['ProjectPlan'], 'ProjectBudgetTypeConfig'],'project'])->find($task['from_id']);
            if (empty($model)) {
                return "找不到该/预算，请联系管理员";
            }
            $zongjine = 0;
            if(count($model->pb->ProjectBudgetPlanConfig) > 0){
                foreach ($model->pb->ProjectBudgetPlanConfig as $key=>$value){
                    $zongjine+=$value['sum_of_money'];
                }
            }
            View::assign('zongjine', $zongjine);
            $src = "detail/budget_detail";
        }else if ($task['from_table'] == "overtime"){
           $model = \app\admin\model\Overtime::find($task['from_id']);
            if (empty($model)) {
                return "找不到该数据，请联系管理员";
            }
            $src = "detail/overtime_detail";
        }else { //其他
            $model = "";
            $src = "";
        }
        $instance = FlowInstance::find($task['instanceid']);
        $originator = \app\admin\model\Admin::find($instance['originator']);
        //历史审批
        $common = new \app\admin\model\Common($task['from_id'], $task['from_table']);
        $data = $common->getCheckFlow();
        if ($request->isAjax()) {
            $row = Db::name($table)->find($ids);
            $data = $request->param();
            if ($data['status'] == -1 || $data['status'] == "-1") {
                //请假
                if ($task['from_table'] == "vacations") { //请假或者调休
                    $vacation = [
                        'id' => $data['vacation_id'],
                        'alternative_title' => $data['alternative_title'],
                        'start_time' => $data['start_time'],
                        'end_time' => $data['end_time'],
                        'remark' => $data['remark'],
                        'status' => 1
                    ];
                    if ($data['alternative_title'] == '调休'){
                        $vacation['corresponding'] = implode(',',$data['corresponding']);
                        $overtime = new Overtime();
                        $syhsc    = $overtime->where('id', 'in', $data['corresponding'])->select()->each(function ($item, $key) {
                            $item['is_leave'] = 1; //拒绝后状态改为未使用状态
                        })->toArray();
                        $overtime->saveAll($syhsc);
                    }
                    //更改当前数据
                    \app\admin\model\Vacation::update($vacation);
                }
                if ($task['from_table'] == "applies") {
                    $model = \app\admin\model\Applies::with(['typeName'])->find($task['from_id']);
                    if (empty($model)) {
                        return "找不到该资源";
                    }
                    if ($model->typeName->name == "借款") {
                        $jk_data = $request->only(['jk_fs', 'jk_money', 'sk_name', 'sk_zh', 'sk_khh', 'sk_content']);
                        $jk_data['id'] = $request->param('jk_id');
                        Money::update($jk_data);
                    }
                    if ($model->typeName->name == "用章") {
                        $yz_data = [
                            'id' => $data['yz_id'],
                            'name' => $data['yz_name'],
                            'yz_content' => $data['yz_content'],
                        ];
                        Zhang::update($yz_data);
                    }
                    if ($model->typeName->name == "用车") {
                        $che_data = [];
                        $from_id = $task['from_id'];
                        foreach ($data['yc_id'] as $key=>$v){
                            $che_data[$key]['start_address'] = $data['start_address'][$key];
                            $che_data[$key]['applies_id'] = $from_id;
                            $che_data[$key]['plan_lx'] = $data['plan_lx'][$key];
                            $che_data[$key]['start_time'] = $data['start_time'][$key];
                            $che_data[$key]['end_time'] = $data['end_time'][$key];
                            $che_data[$key]['day'] = $data['day'][$key];
                            $che_data[$key]['che_dj'] = $data['che_dj'][$key];
                            $che_data[$key]['che_zongjia'] = $data['che_zongjia'][$key];
                            $che_data[$key]['sj_name'] = $data['sj_name'][$key];
                            $che_data[$key]['sj_phone'] = $data['sj_phone'][$key];
                            $che_data[$key]['ycr'] = $data['ycr'][$key];
                        }
                        $che = new Che();
                        if ($che_data) {
                            $res_del = Che::destroy(function ($query) use ($from_id) {
                                $query->where('applies_id', $from_id);
                            },true); //先强制删除
                            if ($res_del) {
                                $che->saveAll($che_data); //在新增
                            }
                        }
                    }
                    if ($model->typeName->name == "采购") {
                        $from_id = $task['from_id'];
                        $cg_data = [];
                        foreach ($data['cg_id'] as $key=>$v){
                            $cg_data[$key]['cg_guige'] = $data['cg_guige'][$key];
                            $cg_data[$key]['applies_id'] = $from_id;
                            $cg_data[$key]['cg_num'] = $data['cg_num'][$key];
                            $cg_data[$key]['cg_dj'] = $data['cg_dj'][$key];
                            $cg_data[$key]['cg_zongjia'] = $data['cg_zongjia'][$key];
                            $cg_data[$key]['cg_content'] = $data['cg_content'][$key];
                        }
                        $caigou = new Caigou();
                        if ($cg_data) {
                            $res_del = Caigou::destroy(function ($query) use ($from_id) {
                                $query->where('applies_id', $from_id);
                            }); //先强制删除
                            if ($res_del) {
                                $caigou->saveAll($cg_data); //在新增
                            }
                        }
                    }
                    \app\admin\model\Applies::update(['id'=>$task['from_id'],'status'=>1]);
                }
                if($task['from_table'] == 'projects'){
                    $pro_data = [
                        'id'=>$task['from_id'],
                        'name'=>$data['name'],
                        'period'=>$data['period'],
                        'content'=>$data['content'],
                        'status'=>1
                    ];
                    Item::update($pro_data);
                    Budget::where('project_id',$task['from_id'])->update([
                        'name'=>$data['name'],
                        'period'=>$data['period'],
                        'content'=>$data['content'],
                    ]);
                }
                if($task['from_table'] == "budget"){
                    if (array_key_exists('project_id', $data)) {

                        //项目基本信息
                        $project_id = $data['project_id'];
                        $budget_id = $data['budget_id'];
                        $budget = Budget::find($budget_id);
                        $project_budget_id = $budget->project_budget_id ?? 0;
                        $data_budget = $request->only([
                            'name',
                            'sample_num',
                            'execution_area',
                            'start_time',
                            'end_time',
                            'sample_num'
                        ]);

//                        Item::update([
//                            'name' => $data['name'],
//                            'content' => $data['content'],
//                            'status' => 1
//                        ], ['id' => $project_id]);        //更新项目表
                        ProjectBudget::where(['id' => $project_budget_id])->update($data_budget);//更新项目表

                        Budget::where(['id' => $budget_id])->update(['name' => $data['name'], 'status' => 1, 'content' => $data['content']]);
                        //项目类型
                        $type_data = [];
                        foreach ($data['type_id'] as $key => $v) {
                            $type_data[$key]['project_id'] = $data['project_id'];
                            $type_data[$key]['project_budget_id']= $project_budget_id;
                            $type_data[$key]['type_name']= $data['type_name'][$key];
                            $type_data[$key]['main_sample_num'] = $data['main_sample_num'][$key];
                            $type_data[$key]['enlarge_sample_num'] = $data['enlarge_sample_num'][$key];
                        }
                        $type_config = new ProjectBudgetTypeConfig();
                        if ($type_data) {
                            $res_del = ProjectBudgetTypeConfig::destroy(function ($query) use ($project_budget_id) {
                                $query->where('project_budget_id',$project_budget_id);
                            }); //先删除
                            if ($res_del) {
                                $type_config->saveAll($type_data); //在新增
                            }
                        }
                        //计划成本
                        $config_data = [];
                        foreach ($data['config_id'] as $key => $v) {
                            $config_data[$key]['project_id'] = $data['project_id'];
                            $config_data[$key]['project_budget_id'] = $project_budget_id;
                            $config_data[$key]['cost_id'] = $data['cost_id'][$key];
                            $config_data[$key]['num'] = $data['num'][$key];
                            $config_data[$key]['unit_price']= $data['unit_price'][$key];
                            $config_data[$key]['sum_of_money'] = $data['num'][$key] * $data['unit_price'][$key];
                            $config_data[$key]['remark'] = $data['remark'][$key];
                        }
                        $plan_config = new ProjectBudgetPlanConfig();
                        if ($config_data) {
                            $res_del = ProjectBudgetPlanConfig::destroy(function (
                                $query
                            ) use ($project_budget_id) {
                                $query->where('project_budget_id',
                                    $project_budget_id);
                            }); //先删除
                            if ($res_del) {
                                $plan_config->saveAll($config_data);
                            }
                        }
                    }
                }
            }

            if (!empty($data['journal_level_id'])) {
                $row['journal_level_id'] = $data['journal_level_id'];
            }
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validate($validate);
                }
                $this->flow = new FlowEngine($schme['flowcode']);
                $this->flow->next($taskid, $row, $data['comment']);
                return json(['code' => 200, 'url' => '', 'msg' => '审核成功']);
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        View::assign('journal_level', $journal_level);
        View::assign('table', $table);
        View::assign('ids', $ids);
        View::assign('task', $task);
        View::assign('plan', $plan);
        View::assign('schme', $schme);
        View::assign('flowCode', $schme['flowcode']);
        View::assign("history", $data['history']);
        View::assign("mode", $mode);
        View::assign("instance", $instance);
        View::assign("row", $row);
        View::assign("originator", $originator);
        View::assign("auth", $this->auth);
        View::assign("model", $model);
        View::assign('cg_type', $cg);
        return View::fetch($src);
    }


    //拒绝流程
    public function refuse(Request $request)
    {
        if ($request->isAjax()) {
            $taskid = $request->param('taskid');
            $task = null;
            $mode = $request->param('mode');
            if ($mode == 'view') {
                $task = $this->task->where(['id' => $taskid])->find();
            } else {
                $task = $this->task->where(['id' => $taskid])->where('status', 0)->find();
            }
            if (!$task)
                return json(['code' => 400, 'url' => '', 'msg' => '找不到当前任务']);
            try {
                $schme = $this->scheme->find($task['flowid']);
                $comment = $request->param('comment');
                $this->flow = new FlowEngine($schme['flowcode']);
                $this->flow->refuse($taskid, $comment);
                return json(['code' => 200, 'url' => '', 'msg' => '审核成功']);
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
    }

    //流程图
    public function flowchart(Request $request)
    {
        $taskid = $request->param('taskid');
        $this->task = new FlowTask();
        $this->scheme = new \app\admin\model\Scheme();
        $task = $this->task->find($taskid);
        $activityId = $task['stepid'];
        $flowcode = $request->param('flowcode');
        if (!$flowcode) {
            $this->error(('No Results were found'));
        }

        $row = $this->scheme->where('flowcode', $flowcode)->find();
        $taskList = Db::name('flow_task')
            ->alias('main')
            ->join('admins admin', 'admin.id=main.receiveid', 'LEFT')
            ->where('instanceid', $task['instanceid'])
            ->field(["main.instanceid", "main.stepid", "main.status", "admin.nickname", "main.completedtime", "main.createtime"])
            ->order('main.createtime', 'desc')
            ->select();
//   $abc = is_array('taskList') ? 'taskList' : ['taskList' => $taskList];
        View::assign('taskList', $taskList);
        View::assign("activityId", $activityId);
        View::assign("flowcontent", $row['flowcontent']);
        View::assign("flowContent", $row['flowcontent']);
        return View::fetch();
    }

    //查看详情信息
    public function check(Request $request)
    {
        $data = $request->param();
        $task = $this->task->find($data['taskid']);
        if ($task['from_table'] == "vacations") {
            $model = \app\admin\model\Vacation::checkDetail($task['from_id']);
            View::assign('model', $model);
            return View::fetch('administration/vacation/vacation_detail');
        } else if ($task['from_table'] == "applies") {
            $item = \app\admin\model\Applies::checkDetail($task['from_table'], $task['from_id']);
            View::assign('model', $item);
            return View::fetch('administration/apply/sh_detail');
        } else if ($task['from_table'] == "journals") {
            $journal_type = JournalType::select();
            $journal_level = JournaLevel::select();
            View::assign('journal_type', $journal_type);
            View::assign('journal_level', $journal_level);
            $model = WorkJournal::with(['JournalType', 'JournaLevel', 'Admin'])->find($task['from_id']);
            View::assign('model', $model);
            return View::fetch('journal/detail');
        } else if ($task['from_table'] == "projects") {
            $model = Item::find($task['from_id']);
            $group = AuthGroup::where(['level' => 2, 'status' => 1])->select();
            View::assign('group', $group);
            View::assign('model', $model);
            return View::fetch('project/detail');
        } else if ($task['from_table'] == "budget") {
            $project = Budget::find($task['from_id']);
            $model = Item::with(['ProjectBudget' => ['ProjectBudgetPlanConfig' => ['ProjectPlan'], 'ProjectBudgetTypeConfig']])->find($project['project_id']);
            View::assign('model', $model);
            return View::fetch('project/examine_budget_detail');
        }
    }
}
